package com.yuedou.api.controller.mer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuedou.api.constant.ResponseCode;
import com.yuedou.api.controller.platform.BaseController;
import com.yuedou.api.entity.dto.ProductTypeDto;
import com.yuedou.api.entity.mer.*;
import com.yuedou.api.entity.platform.*;
import com.yuedou.api.entity.product.OrderAppraise;
import com.yuedou.api.entity.product.Product;
import com.yuedou.api.entity.sys.SysUser;
import com.yuedou.api.entity.wxuser.User;
import com.yuedou.api.entity.wxuser.UserAddress;
import com.yuedou.api.service.platfom.*;
import com.yuedou.api.service.product.OrderAppraiseService;
import com.yuedou.api.service.product.ProductService;
import com.yuedou.api.service.product.ProductTypeService;
import com.yuedou.api.service.sys.SysErrorService;
import com.yuedou.api.service.sys.SysUserService;
import com.yuedou.api.service.wxuser.*;
import com.yuedou.api.service.mer.*;
import com.yuedou.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  商家相关的接口
 *@Date 2025-01-17
 */
@Component
@RestController
@RequestMapping("/mer")//url:模块/资源/{}/细分
public class MerController extends BaseController {

    @Resource
    private MerService merService;
    @Resource
    private MerUserService merUserService;
    @Resource
    private OrderAppraiseService orderAppraiseService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private UserService userService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserCollectionService userCollectionService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private SearchDataService searchDataService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private CityService cityService;
    @Resource
    private DistrictService districtService;
    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址
    @Value("${web.imgPrefixOss}")
    private String imgPrefixOss;//图片地址
    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    /**
     * 充电测试
     * @return
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

//            List<UserMp> users = userMpService.selectUserMpList(mer_id);
//            merCategoryService.resetCategory();

            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功" ),true,false);

        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            int cateId = jsonRequest.containsKey("cate_id") ? jsonRequest.getInt("cate_id") : 0;
            int cateChildId = jsonRequest.containsKey("cate_child_id") ? jsonRequest.getInt("cate_child_id") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String sort = jsonRequest.containsKey("sort") ? jsonRequest.getStr("sort") : null;

            int offset = (pageIndex - 1) * pageSize;
            List<Mer> list = merService.selectByState(user_id,0,cateId,cateChildId,keyword,0,sort,offset,pageSize,longitude,latitude);
            Map<String,Object> map = new HashMap<>();
            map.put("mers",list);

            List<ProductTypeDto> types = productTypeService.getChildOptions(cateId,cateChildId);
            map.put("serviceTypes",types);

            if(CollUtil.isNotEmpty(list)){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",0,map),false,false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/search/list")
    public JSONObject searchList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/search/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int userId = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;


            if(StrUtil.isNotEmpty(keyword)){
                SearchData searchData = new SearchData();
                searchData.setCreateTime(new Date());
                searchData.setFromType("mer");
                searchData.setUserId(userId);
                searchData.setSearchWord(keyword);
                searchDataService.save(searchData);
            }

            List<Mer> list = merService.getListBySearch(userId,keyword,shop_type,pageIndex,pageSize,longitude,latitude);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 我的商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/myList")
    public JSONObject myList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/myList 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            Integer shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;
            Integer pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            Integer pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            int offset = (pageIndex - 1) * pageSize;

            List<Map<String,Object>> merNames = new ArrayList<>();
            List<Mer> list = merService.selectMyList(user_id,shop_type,offset,pageSize);
            if(CollUtil.isNotEmpty(list)){
                for (Mer mer : list){
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("text",mer.getShopName());
                    map1.put("value",mer.getId());
                    merNames.add(map1);
                    if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                        mer.setShopLogo(imgPrefixOss + mer.getShopLogo());
                    }
                }
            }
            map.put("mer_names",merNames);
            map.put("mers",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  移交商家给其他人
     * @param
     * @throws Exception
     */
    @PostMapping(value="/exChangeUser")
    public JSONObject exChangeUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/exChangeUser 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int exchange_user_id = jsonRequest.containsKey("exchange_user_id") ? jsonRequest.getInt("exchange_user_id") : 0;

            if(exchange_user_id == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择移交用户"),true,true);
            }
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }


            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id, mer_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"无移交权限"),true,true);
            }

            User exchangUser = userService.findById(exchange_user_id);
            if(exchangUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"移交用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser!=null){
                merUser.setSysUserId(sysUser.getUserId());
            }

            merUser.setUserId(exchange_user_id);
            merUser.setNickName(exchangUser.getNickName());
            boolean bl = merUserService.updateById(merUser);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"移交成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"移交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  存在多个商家的情况下，设置默认的显示商家
     * @param
     * @throws Exception
     */
    @PostMapping(value="/changeDefault")
    public JSONObject changeDefault(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/exChangeUser 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id, mer_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该商家权限"),true,true);
            }

            List<MerUser> merUsers = merUserService.selectListByColumn("user_id",user_id);
            if(CollUtil.isNotEmpty(merUsers)){
                for(MerUser merUser1 : merUsers){
                    //先重置 默认状态 都未0
//                    merUserService.update(merUser1,new LambdaUpdateWrapper<MerUser>()
//                            .set(MerUser::getIsDefault, 0).eq(MerUser::getUserId, merUser1.getUserId()));
                    merUser1.setIsDefault(0);
                    merUserService.updateById(merUser1);
                }
            }

            merUser.setIsDefault(1);
            boolean bl = merUserService.updateById(merUser);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"切换成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"切换失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家详情信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int address_id = jsonRequest.containsKey("address_id") ? jsonRequest.getInt("address_id") : 0;

            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                mer.setShopLogo(imgPrefixOss + mer.getShopLogo());
            }

            //获取商家的服务（商品）
            List<Product> products = productService.queryProductList(mer.getId(),0);
            mer.setProducts(products);
            mer.setProductCount(products.size());

            List<OrderAppraise> appraises = orderAppraiseService.selectByMerId(mer_id,pageIndex,pageSize);
            map.put("mer",mer);
            map.put("appraises",appraises);
            map.put("appraiseCount",0);
            map.put("user_id",user_id);

            map.put("isCollect",0);
            long isCollect = userCollectionService.getCollectionCountByMerId(user_id,mer_id);
            if(isCollect > 0){
                map.put("isCollect",1);
            }


            map.put("is_in_poly", 0);
            if(address_id > 0){
                UserAddress userAddress = userAddressService.findById(address_id);
                if(userAddress != null){
                    map.put("address_lng", userAddress.getLng());
                    map.put("address_lat", userAddress.getLat());

                    boolean blIsInPoly = merService.isInPoly(mer, userAddress);
                    map.put("is_in_poly", blIsInPoly? 1: 0);
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家详情信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detailByNo")
    public JSONObject detailByNo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/detailByNo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shop_no = jsonRequest.containsKey("shop_no") ? jsonRequest.getStr("shop_no") : null;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude"): 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude"): 0;

            User user = userService.findById(user_id);

            if(shop_no == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            Mer mer = merService.selectByUniqueColumn("shop_no",shop_no);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merAdminUser = merUserService.getMerUserByMerId(mer.getId(), 1);
            map.put("merAdminUser", merAdminUser);


            if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                mer.setShopLogo(imgPrefixOss + mer.getShopLogo());
            }

            map.put("mer",mer);

            map.put("is_has_pay_pwd", 0);
            if(user != null){
                if(StrUtil.isNotEmpty(user.getPayPwd())){
                    map.put("is_has_pay_pwd", 1);
                }
            }

            double distance = GetDistance.GetDistance(mer.getLongitude().doubleValue(),mer.getLatitude().doubleValue(),longitude,latitude);
            map.put("distance", distance);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 商家绑定管理员
     * @param
     * @throws Exception
     */
    @PostMapping(value="/bandMerUser")
    public JSONObject bandMerUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/bandMerUse 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int mer_user_id = jsonRequest.containsKey("mer_user_id") ? jsonRequest.getInt("mer_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getById(mer_user_id);
            if(merUser != null){
                if(merUser.getUserId() == null && merUser.getSysUserId() != null){
                    merUser.setUserId(user_id);
                    boolean bl = merUserService.updateById(merUser);
                    if(bl){
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"激活绑定成功"),true,true);
                    }else{
                        result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"激活绑定失败，请重试"),true,true);
                    }
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已绑定，无需重复绑定"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"账号不存在，联系管理员"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家入驻
     * @param
     * @throws Exception
     */
    @PostMapping(value="/register")
    public JSONObject register(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/register 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shopName = jsonRequest.containsKey("shopName") ? jsonRequest.getStr("shopName") : null;
            String leaderName = jsonRequest.containsKey("leaderName") ? jsonRequest.getStr("leaderName") : null;
            String phoneNum = jsonRequest.containsKey("phoneNum") ? jsonRequest.getStr("phoneNum") : null;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String address = jsonRequest.containsKey("address") ? jsonRequest.getStr("address") : null;
            int ag_id = jsonRequest.containsKey("ag_id") ? jsonRequest.getInt("ag_id") : 0;

            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }


            Mer mer = merService.getMerByUserIdUnCheck(user_id);
            if(mer != null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您有待审核的商家，请耐心等待"),true,true);
            }

//            MerUser merUser = merUserService.getMerUser(user_id);
//            if(merUser != null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已申请商家"),true,true);
//            }

            mer = new Mer();
            String shopNo = "M" + new Date().getTime();
            mer.setUserId(user_id);
            mer.setShopNo(shopNo);
            mer.setShopName(shopName);
            mer.setShopType(0);
            mer.setState(1);
            mer.setCateId(2);
            mer.setLongitude(new BigDecimal(lng));
            mer.setLatitude(new BigDecimal(lat));
            mer.setCreateTime(new Date());
            mer.setAddress(address);
            mer.setKeyWord(keyword);
            mer.setLeaderName(leaderName);
            mer.setTelphone(phoneNum);
            mer.setServiceStar(0);
            mer.setMaxOrderCount(1000);
            mer.setIsPlatform(0);
            mer.setCheckState(0);



            Province province = provinceService.selectByUniqueColumn("province_name",user.getProvince());
            if(province!=null){
                mer.setProvId(province.getId());
                QueryWrapper<City> qwCity = new QueryWrapper<>();
                qwCity.eq("province_id",province.getId());
                qwCity.like("city_name", user.getCity());
                qwCity.last("limit 1");
                City city = cityService.getOne(qwCity);
                if(city!=null){
                    mer.setCityId(city.getId());
                    if(StrUtil.isNotEmpty(user.getDistrict())){
                        QueryWrapper<District> qwDis = new QueryWrapper<>();
                        qwDis.eq("city_id",city.getId());
                        qwDis.like("district_name", user.getDistrict());
                        qwDis.last("limit 1");
                        District district = districtService.getOne(qwDis);
                        if(district!=null){
                            mer.setDistrictId(district.getId());
                        }
                    }
                }
            }

            mer = merService.getLocationInfo(mer);

            int ret = merService.register(mer,user,ag_id);
            if(ret > 0){

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"已提交申请",mer.getId()),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /** 商家入驻的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImgRepair(@RequestParam("mer_id") int mer_id,@RequestParam("type") int type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "商家不存在"), true, true);
            }

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            String imgUrls= "";
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certUrl = maps.get(key);
                        if (!certUrl.isEmpty()) {
                            String prefix = certUrl.getOriginalFilename().substring(certUrl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "shop_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certUrl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_MER_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

//                                        OssUtil.upload(certUrl.getInputStream(),fileName,upload_type);

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certUrl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        imgUrls += img_key + ",";
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            if(StrUtil.isNotEmpty(imgUrls)){
                imgUrls = imgUrls.substring(0,imgUrls.length() - 1);
            }

            if(type == 0){
                mer.setShopLogo(imgUrls);
            }else if(type == 1){
                mer.setCodeImg(imgUrls);
            } else if(type == 2){
                mer.setIdCardImgBefore(imgUrls);
            } else if(type == 3){
                mer.setIdCardImgAfter(imgUrls);
            } else if(type == 4){
                mer.setSignImg(imgUrls);
            }
            boolean bl = merService.updateById(mer);
            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "图片上传失败"), true, true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("terminal/uploadImgRepair",e);
        }
        return result;
    }

}
